package com.example.recyclerviewtest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private List<Fruit> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //准备数据
        InitFruit();
        //获取recyclerview控件
        RecyclerView rv = (RecyclerView) findViewById(R.id.recycler_view);
        //为RecyclerView设置布局方式--线性（默认纵向排列）
//        LinearLayoutManager lm = new LinearLayoutManager(MainActivity.this);
        //设置方向
//        lm.setOrientation(LinearLayoutManager.HORIZONTAL);
//        rv.setLayoutManager(lm);
        // 瀑布流布局
        StaggeredGridLayoutManager sgm = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        rv.setLayoutManager(sgm);

        // 创建适配器
        FruitAdapter fa = new FruitAdapter(list);
        //为RecyclerView设置适配器
        rv.setAdapter(fa);
    }

    private void InitFruit(){
        for (int i = 0; i < 2; i++) {
            Fruit f1 = new Fruit(getRadomName("apple1"),R.drawable.img);
            list.add(f1);
            Fruit f2 = new Fruit(getRadomName("apple2"),R.drawable.img);
            list.add(f2);
            Fruit f3 = new Fruit(getRadomName("apple3"),R.drawable.img);
            list.add(f3);
            Fruit f4 = new Fruit(getRadomName("apple4"),R.drawable.img);
            list.add(f4);
            Fruit f5 = new Fruit(getRadomName("apple5"),R.drawable.img);
            list.add(f5);
            Fruit f6 = new Fruit(getRadomName("apple6"),R.drawable.img);
            list.add(f6);
            Fruit f7 = new Fruit(getRadomName("apple7"),R.drawable.img);
            list.add(f7);
            Fruit f8 = new Fruit(getRadomName("apple8"),R.drawable.img);
            list.add(f8);
        }
    }
    private String getRadomName(String name){
        Random r = new Random();
        //产生1~10的随机数
        int len = r.nextInt(10) + 1;
        StringBuilder sbuilder = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sbuilder.append(name);
        }
        return sbuilder.toString();
    }
}